package artid.com.arttogo.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import artid.com.arttogo.R;
import artid.com.arttogo.activity.AucOrgDetActivity;
import artid.com.arttogo.bean.JigouList;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.view.alphabeticalindex.AlphabeticalIndexParse;
import artid.com.arttogo.view.alphabeticalindex.IndexesMechanismBean;
import artid.com.arttogo.view.alphabeticalindex.IndexesMechanism_Adapter;
import artid.com.arttogo.view.alphabeticalindex.MyLetterAlistView;
import artid.com.arttogo.view.alphabeticalindex.PinyinComparator_Mechanism;

import static android.R.attr.data;


/**
 * 项目名称：ArtworkArt
 * 类名称：AlphabeticalIndex_Activity
 * 类描述：拍卖字母索引
 * 创建人：耿卫斌
 * 创建时间：2017-2-24 下午3:38:46
 */
public class AucAlphaActivity extends BaseFragment {
    private Context mContext;
    private View mView;
    private ListView mListView;
    private LinearLayout noDataLL;
    private TextView noDataHintTv;
    // 右侧A-Z字母列表
    private MyLetterAlistView letterListView;
    // dialog text
    private TextView num, overlay;
    // 估计是弹出dialog线程
    private OverlayThread overlayThread;
    //机构Adapter
    private IndexesMechanism_Adapter adapter;
    private Handler handler;
    String id;
    /**
     * 汉字转换成拼音的类
     */
    private List<IndexesMechanismBean> dateList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator_Mechanism pinyinComparator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Bundle args = getArguments();
        id = args != null ? args.getString("id") : "";
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        mView = inflater.inflate(R.layout.activity_alphabeticalindex, null);
        mContext = getActivity();
        initView();
        return mView;
    }

    private void initView() {
        mContext = getActivity();
        handler = new Handler();
        overlayThread = new OverlayThread();
        num = (TextView) mView.findViewById(R.id.AlphabeticalIndex_num);
        mListView = (ListView) mView.findViewById(R.id.AlphabeticalIndex_ListView);
        letterListView = (MyLetterAlistView) mView.findViewById(R.id.AlphabeticalIndex_MyLetterAlistView);
        letterListView.setVisibility(View.GONE);
        noDataLL = (LinearLayout) mView.findViewById(R.id.ll_hint);
        noDataHintTv= (TextView) mView.findViewById(R.id.ll_hint_tv);
        getData();
        /** 给ListView设置adapter **/
        // 根据拼音排序

    }

    void getData() {

        VolleyBasic.getInstance(getActivity()).post(Cache.jigouList,
                VolleyMap.getInstance().jigouList("2", "", ""), JigouList.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        List<JigouList> list = (List<JigouList>) vd.getList();
                        num.setText(list.size() + "家");
                        List<IndexesMechanismBean> listBean = new ArrayList<IndexesMechanismBean>();
                        for (int i = 0; i < list.size(); i++) {
                            IndexesMechanismBean bean11 = new IndexesMechanismBean();
                            bean11.setName(list.get(i).getSeller_name());
                            bean11.setId(list.get(i).getId());
                            listBean.add(bean11);
                        }
                        final List<IndexesMechanismBean> listClick = listBean;
                        pinyinComparator = new PinyinComparator_Mechanism();
                        dateList = new ArrayList<IndexesMechanismBean>();
                        dateList = filledData(listBean);
                        Collections.sort(dateList, pinyinComparator);// 根据a-z进行排序源数据
                        if (dateList != null && dateList.size() != 0) {
                            List<String> letterAlistView_list = new ArrayList<String>();
                            for (int i = 0; i < dateList.size(); i++) {
                                //先将数据添加到集合
                                letterAlistView_list.add(dateList.get(i).getSortLetters().toString());
                            }
                            //去重
                            for (int i = 0; i < letterAlistView_list.size() - 1; i++) {
                                for (int j = letterAlistView_list.size() - 1; j > i; j--) {
                                    if (letterAlistView_list.get(j).equals(letterAlistView_list.get(i))) {
                                        letterAlistView_list.remove(j);
                                    }
                                }
                            }
                            String[] letterAlistView_Data = new String[letterAlistView_list.size()];
                            for (int i = 0; i < letterAlistView_list.size(); i++) {
                                letterAlistView_Data[i] = letterAlistView_list.get(i).toString();
                            }
                            letterListView.setData(letterAlistView_Data);
                            letterListView.setVisibility(View.VISIBLE);
                            noDataLL.setVisibility(View.GONE);
                        }else{
                            noDataHintTv.setText("目前还没有相关内容");
                            noDataLL.setVisibility(View.VISIBLE);
                        }
                        adapter = new IndexesMechanism_Adapter(mContext, dateList);
                        mListView.setAdapter(adapter);
                        mListView.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> arg0,
                                                    View arg1, int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(mContext, AucOrgDetActivity.class);
                                intent.putExtra("id", listClick.get(arg2).getId());
                                startActivity(intent);
                            }
                        });
                        initOverlay();
                        letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
                        //List<ArtList> list = (List<ArtList>)vd.getList();
                        //if (list.isEmpty()) {
                        //	Config.showTip(MoreCollectionsActivity.this, "无数据");
                        return;
                        //}
                        //ArtistInfo list = (ArtistInfo)vd.getData();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        noDataHintTv.setText("目前还没有相关内容");
                        noDataLL.setVisibility(View.VISIBLE);
                    }
                });


//		pinyinComparator = new PinyinComparator_Mechanism();
//		dateList = new ArrayList<IndexesMechanismBean>();
//		dateList=filledData(setData());
//		Collections.sort(dateList, pinyinComparator);// 根据a-z进行排序源数据
//		adapter = new IndexesMechanism_Adapter(mContext, dateList);
//		mListView.setAdapter(adapter);
//		initOverlay();
//		letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    @SuppressLint("DefaultLocale")
    private List<IndexesMechanismBean> filledData(List<IndexesMechanismBean> date) {
        List<IndexesMechanismBean> mList = new ArrayList<IndexesMechanismBean>();
        for (int i = 0; i < date.size(); i++) {
            IndexesMechanismBean mBean = new IndexesMechanismBean();
            mBean.setName(date.get(i).getName());
            // 汉字转换成拼音
            String pinyin = getFirstSpell(date.get(i).getName());
            try {
                String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    mBean.setSortLetters(sortString.toUpperCase());
                } else {
                    mBean.setSortLetters("#");
                }
            } catch (Exception e) {
                // TODO: handle exception
                //当遇到非法字符的时候会出现报错的问题，所以直接将他设置为#状态
                mBean.setSortLetters("#");
            }
            mList.add(mBean);
        }
        return mList;
    }

    // 右侧A-Z字母监听
    private class LetterListViewListener implements MyLetterAlistView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            // 该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                mListView.setSelection(position);
                overlay.setText(dateList.get(position).getSortLetters());
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 500);
            }
        }
    }

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        overlay = (TextView) inflater.inflate(R.layout.view_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    /**
     * 汉字转换为汉语拼音首字母
     *
     * @return 拼音
     */
    public static String getFirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char curchar : arr) {
            if (curchar > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(curchar);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }


    /**
     * 解析sort_key,封装简拼,全拼
     *
     * @param sortKey
     * @return
     */
    String chReg = "[\\u4E00-\\u9FA5]+";//中文字符串匹配

    public AlphabeticalIndexParse parseSortKey(String sortKey) {
        AlphabeticalIndexParse token = new AlphabeticalIndexParse();
        if (sortKey != null && sortKey.length() > 0) {
            //其中包含的中文字符
            String[] enStrs = sortKey.replace(" ", "").split(chReg);
            for (int i = 0, length = enStrs.length; i < length; i++) {
                if (enStrs[i].length() > 0) {
                    //拼接简拼
                    token.simpleSpell += enStrs[i].charAt(0);
                    token.wholeSpell += enStrs[i];
                }
            }
        }
        return token;
    }
}
